package com.bwie.common.handler;


import com.bwie.common.exceptions.BizException;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @ClassName:
 * @Description: 全局异常处理器
 * @Author: zhuwenqiang
 * @Date: 2024/12/13
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 业务异常处理器
     *
     * @return
     */
    @ExceptionHandler(BizException.class)
    public Result bizExceptionHandler(BizException bizException) {
        log.error("业务处理异常，异常信息：{}", bizException.getMessage());
        return Result.error(bizException.getMessage());
    }

    /**
     * 参数不合法异常处理器
     *
     * @param methodArgumentNotValidException
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException) {
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String errMsg = "";
        for (ObjectError allError : allErrors) {
            errMsg += "," + allError.getDefaultMessage();
        }
        errMsg = errMsg.substring(1);
        return Result.error(errMsg);
    }

}
